package com.google.code.mongoDao;

import org.apache.log4j.Logger;

import com.mongodb.DB;
import com.mongodb.DBObject;

/**
 * Follows proper mongo database idiom to ensure consistency via a "consistent request"
 * 
 * @author MWaschkowski
 *
 */
public class DBCommandRunner {

  private static Logger log = Logger.getLogger(DBCommandRunner.class);
  
  /**
   * Runs the specified command within a particular request using the proper mongo idiom
   * for a verified database action.
   * 
   * ie. checks for an error after action done
   * 
   * Throws a runtime exception if an error occurred, this may be modified to a specific
   * exception in the future.
   * 
   * @param db
   * @param command
   * @return
   */
  public Object runDatabaseCommand(DB db, Command command){
    return runDatabaseCommand(db, command, true);
  }
  
  public Object runDatabaseCommand(DB db, Command command, boolean logErrors){
    Object object = null;
    try{
      db.requestStart();
      object = command.execute();
      DBObject databaseObject = db.getLastError();
      if(databaseObject.get("err") != null){
        throw new RuntimeException("Err=" + databaseObject.get("err"));
      }
    }catch(Exception e){
      if(logErrors){
        log.fatal(e); 
        log.fatal(command);
      }
      throw new RuntimeException(e);
    }finally{
      db.requestDone();
    }
    
    return object;
  }
  
}
